import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

// 简化的marked配置，避免复杂的自定义渲染器导致问题
marked.setOptions({
  highlight: function(code, lang) {
    const codeStr = String(code || '')
    const langStr = String(lang || '')
    
    if (langStr && hljs.getLanguage(langStr)) {
      try {
        return hljs.highlight(codeStr, { language: langStr }).value
      } catch (err) {
        return codeStr
      }
    }
    
    try {
      return hljs.highlightAuto(codeStr).value
    } catch (err) {
      return codeStr
    }
  },
  breaks: true,
  gfm: true,
  tables: true,
  sanitize: false
})

// 改进的渲染函数，正确处理代码块
function postProcessHTML(html: string): string {
  return html
    // 首先处理代码块（pre > code），添加复制按钮和样式
    .replace(/<pre><code class="language-(\w+)">([\s\S]*?)<\/code><\/pre>/g, (match, lang, code) => {
      return `<div class="code-block-container my-4">
        <div class="code-block-header bg-gray-100 dark:bg-gray-800 px-4 py-2 text-xs text-gray-600 dark:text-gray-400 border-b border-gray-200 dark:border-gray-600 rounded-t-lg flex items-center justify-between">
          <span class="font-mono">${lang || 'plaintext'}</span>
          <button onclick="copyCode(this)" class="copy-btn text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
            </svg>
          </button>
        </div>
        <pre class="code-block bg-gray-50 dark:bg-gray-900 p-4 overflow-x-auto rounded-b-lg border border-gray-200 dark:border-gray-600"><code class="language-${lang || 'plaintext'}">${code}</code></pre>
      </div>`
    })
    // 处理没有语言标识的代码块
    .replace(/<pre><code>([\s\S]*?)<\/code><\/pre>/g, (match, code) => {
      return `<div class="code-block-container my-4">
        <div class="code-block-header bg-gray-100 dark:bg-gray-800 px-4 py-2 text-xs text-gray-600 dark:text-gray-400 border-b border-gray-200 dark:border-gray-600 rounded-t-lg flex items-center justify-between">
          <span class="font-mono">plaintext</span>
          <button onclick="copyCode(this)" class="copy-btn text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
            </svg>
          </button>
        </div>
        <pre class="code-block bg-gray-50 dark:bg-gray-900 p-4 overflow-x-auto rounded-b-lg border border-gray-200 dark:border-gray-600"><code>${code}</code></pre>
      </div>`
    })
    // 为标题添加样式类
    .replace(/<h1>/g, '<h1 class="text-3xl font-bold text-gray-900 dark:text-gray-100 mt-8 mb-6 border-b-2 border-gray-200 dark:border-gray-700 pb-3">')
    .replace(/<h2>/g, '<h2 class="text-2xl font-semibold text-gray-900 dark:text-gray-100 mt-6 mb-4 border-b border-gray-200 dark:border-gray-700 pb-2">')
    .replace(/<h3>/g, '<h3 class="text-xl font-semibold text-gray-900 dark:text-gray-100 mt-6 mb-4">')
    .replace(/<h4>/g, '<h4 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mt-4 mb-3">')
    .replace(/<h5>/g, '<h5 class="text-base font-semibold text-gray-900 dark:text-gray-100 mt-4 mb-3">')
    .replace(/<h6>/g, '<h6 class="text-sm font-semibold text-gray-900 dark:text-gray-100 mt-4 mb-3">')
    // 为段落添加样式类
    .replace(/<p>/g, '<p class="mb-4 leading-relaxed text-gray-700 dark:text-gray-300">')
    // 为列表添加样式类
    .replace(/<ul>/g, '<ul class="list-disc list-inside space-y-2 my-4 ml-4 text-gray-700 dark:text-gray-300">')
    .replace(/<ol>/g, '<ol class="list-decimal list-inside space-y-2 my-4 ml-4 text-gray-700 dark:text-gray-300">')
    // 为链接添加样式类
    .replace(/<a /g, '<a class="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline transition-colors" ')
    // 为行内代码添加样式类（注意：这个要在代码块处理之后）
    .replace(/<code(?![^>]*class="language-)>/g, '<code class="bg-gray-100 dark:bg-gray-800 text-pink-600 dark:text-pink-400 px-2 py-1 rounded text-sm font-mono">')
    // 为引用块添加样式类
    .replace(/<blockquote>/g, '<blockquote class="border-l-4 border-blue-500 dark:border-blue-400 pl-4 py-2 my-6 bg-blue-50 dark:bg-blue-900/20 italic text-gray-700 dark:text-gray-300 rounded-r-lg">')
    // 为表格添加样式类
    .replace(/<table>/g, '<div class="table-container my-6 overflow-x-auto"><table class="table-auto w-full border-collapse border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden shadow-sm">')
    .replace(/<\/table>/g, '</table></div>')
    .replace(/<thead>/g, '<thead class="bg-gray-50 dark:bg-gray-700">')
    .replace(/<tbody>/g, '<tbody class="bg-white dark:bg-gray-800">')
    .replace(/<th>/g, '<th class="px-4 py-3 text-left font-semibold text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600">')
    .replace(/<td>/g, '<td class="px-4 py-3 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600">')
    // 为强调元素添加样式类
    .replace(/<strong>/g, '<strong class="font-semibold text-gray-900 dark:text-gray-100">')
    .replace(/<em>/g, '<em class="italic text-gray-800 dark:text-gray-200">')
    // 为水平线添加样式类
    .replace(/<hr>/g, '<hr class="border-t-2 border-gray-200 dark:border-gray-700 my-8">')
}

// 导出渲染函数
export function renderMarkdown(markdown: string): string {
  if (!markdown || !markdown.trim()) {
    return '<p class="text-gray-500 dark:text-gray-400 italic">开始编写您的 Markdown 文档...</p>'
  }
  
  try {
    // 使用基础的marked渲染
    const rawHTML = marked.parse(markdown)
    
    // 确保返回字符串并进行后处理
    const htmlString = typeof rawHTML === 'string' ? rawHTML : String(rawHTML)
    
    // 应用样式后处理
    return postProcessHTML(htmlString)
  } catch (error) {
    console.error('Markdown渲染错误:', error)
    return `<div class="error-message bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 my-4">
      <h4 class="text-red-800 dark:text-red-200 font-semibold mb-2">Markdown 渲染错误</h4>
      <p class="text-red-600 dark:text-red-300 text-sm">${error instanceof Error ? error.message : '未知错误'}</p>
      <pre class="mt-2 text-xs text-gray-600 dark:text-gray-400">${markdown}</pre>
    </div>`
  }
}

// 全局复制代码功能
if (typeof window !== 'undefined') {
  (window as any).copyCode = function(button: HTMLButtonElement) {
    const codeBlock = button.closest('.code-block-container')?.querySelector('code')
    if (codeBlock) {
      const text = codeBlock.textContent || ''
      navigator.clipboard.writeText(text).then(() => {
        const originalHTML = button.innerHTML
        button.innerHTML = `<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
        </svg>`
        button.classList.add('text-green-600')
        setTimeout(() => {
          button.innerHTML = originalHTML
          button.classList.remove('text-green-600')
        }, 2000)
      }).catch(err => {
        console.error('复制失败:', err)
      })
    }
  }
}